<template>
  <div class="container">
    <div class="change-input">
      <h2 class="title">修改密码</h2>
      
      <div class="input-group">
        <span>请输入账号</span>
        <el-input 
          v-model="account" 
          class="input-field"
          placeholder="请输入账号" 
          @blur="validateAccount"
        />
        <p v-if="accountError" class="error">请输入账号</p>
      </div>
      
      <div class="input-group">
        <span>请输入原密码</span>
        <el-input 
          v-model="oldPassword" 
          class="input-field"
          placeholder="请输入原密码" 
          type="password"
          @blur="validateOldPassword"
        />
        <p v-if="oldPasswordError" class="error">请输入原密码</p>
      </div>
      
      <div class="input-group">
        <span>请输入新密码</span>
        <el-input 
          v-model="newPassword" 
          class="input-field"
          placeholder="请输入新密码" 
          type="password" 
          @blur="validateNewPassword"
        />
        <p v-if="newPasswordError" class="error">密码必须包含数字、字母和特殊字符，长度为8-16位</p>
        <p v-if="oldOrNewError" class="error">新密码不能与原密码相同</p>
      </div>
      
      <div class="input-group">
        <span>请确认新密码</span>
        <el-input 
          v-model="confirmPassword" 
          class="input-field"
          placeholder="请确认新密码" 
          type="password" 
          @blur="validateConfirmPassword"
        />
        <p v-if="confirmPasswordError" class="error">两次输入的密码不一致</p>
      </div>
      
      <el-button 
        type="primary" 
        class="submit-button" 
        @click="submitForm"
        :loading="loading"
        :disabled="!formValid"
      >
        提交
      </el-button>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed } from 'vue';
import request from '@/utils/request';
import { useRouter } from 'vue-router';
import { useAuthStore } from '@/stores/user';
import showMessage from '@/utils/showMessage';
import { useRoute } from 'vue-router'

const route = useRoute()

// 获取 query 参数并解析
const userData = ref<any>() 
userData.value = route.query.userData
console.log(JSON.parse(userData.value)) // 输出用户数据
const useMessage = ref()
useMessage.value = JSON.parse(userData.value)

const router = useRouter();
const authStore = useAuthStore();

const account = ref('');
const oldPassword = ref('');
const newPassword = ref('');
const confirmPassword = ref('');
const loading = ref(false);

const accountError = ref(false);
const oldPasswordError = ref(false);
const newPasswordError = ref(false);
const confirmPasswordError = ref(false);
const oldOrNewError = ref(false);

const validateAccount = () => {
  accountError.value = !account.value.trim();
};

const validateOldPassword = () => {
  oldPasswordError.value = !oldPassword.value.trim();
};

const validateNewPassword = () => {
  const passwordRegex = /^(?=.*[a-zA-Z])(?=.*\d)(?=.*[!@#$%^&*])[A-Za-z\d!@#$%^&*]{8,16}$/;
  newPasswordError.value = !passwordRegex.test(newPassword.value);
  oldOrNewError.value = newPassword.value === oldPassword.value;
};

const validateConfirmPassword = () => {
  confirmPasswordError.value = newPassword.value !== confirmPassword.value;
};

// 计算属性，判断表单是否有效
const formValid = computed(() => {
  return account.value.trim() && 
         oldPassword.value.trim() && 
         newPassword.value.trim() && 
         confirmPassword.value.trim() &&
         !newPasswordError.value && 
         !confirmPasswordError.value &&
         !oldOrNewError.value;
});

const submitForm = async () => {
  if (!formValid.value) return;
  
  loading.value = true;
  
  try {
    const res = await request.post("/user/changePassword", {
      username: account.value,
      password: oldPassword.value,
      newPassword: newPassword.value
    });

    if (res.data.status === "success") {  
      showMessage(res);
      
      // 记录操作日志
      await request.post('/user/insertOperation', {
        username: account.value,
        name: useMessage.value.name,
        organizationID: useMessage.value.organizationID,
        ip: null,
        operationModel: "系统管理",
        operationResult: "修改用户密码",
        operationTime: null,
        operationType: "operation"
      });
      
      // 更新本地存储的密码
      if (authStore.user?.username === account.value) {
        localStorage.setItem('password', newPassword.value);
      }
      
      router.push('/');
    } else {
      showMessage(res);
    }
  } catch (error) {
    console.error('操作失败', error);
    showMessage({ message: '操作失败，请稍后重试', type: 'error' });
  } finally {
    loading.value = false;
  }
};
</script>

<style scoped>
/* 保持原有样式不变 */
.container {
  height: 100vh;
  background-color: #eaf4fc;
  display: flex;
  justify-content: center;
  align-items: center;
  background-image: url('@/assets/image/changePassword.jpg');
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
}

.change-input {
  width: 400px;
  padding: 20px;
  border-radius: 10px;
  background-color: #fff;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
}

.title {
  text-align: center;
  margin-bottom: 20px;
  font-size: 18px;
  color: #333;
}

.input-group {
  margin-bottom: 15px;
}

.input-group span {
  display: block;
  margin-bottom: 5px;
  font-size: 14px;
  color: #555;
}

.input-field {
  width: 100%;
}

.submit-button {
  width: 100%;
  margin-top: 10px;
}

.error {
  color: red;
  font-size: 12px;
  margin-top: 5px;
}
</style>